﻿// BingoTouch Javascript Framework
// Yuxg@bingosoft.net	2012.4~?

jQuery.extend({
    evalJSON: function (strJson) {
        return eval("(" + strJson + ")");
    }
});
jQuery.extend({
    toJSON: function (object) {
        if (object == null)
            return null;
        var type = typeof object;
        if ('object' == type) {
            if (Array == object.constructor)
                type = 'array';
            else if (RegExp == object.constructor)
                type = 'regexp';
            else
                type = 'object';
        }
        switch (type) {
            case 'undefined':
            case 'unknown':
                return;
                break;
            case 'function':
            case 'boolean':
            case 'regexp':
                return object.toString();
                break;
            case 'number':
                return isFinite(object) ? object.toString() : 'null';
                break;
            case 'string':
                return '"' + object.replace(/(\\|\")/g, "\\$1").replace(/\n|\r|\t/g,
      function () {
          var a = arguments[0];
          return (a == '\n') ? '\\n' :
                      (a == '\r') ? '\\r' :
                      (a == '\t') ? '\\t' : ""
      }) + '"';
                break;
            case 'object':
                if (object === null) return 'null';
                var results = [];
                for (var property in object) {
                    var value = jQuery.toJSON(object[property]);
                    if (value !== undefined)
                        results.push(jQuery.toJSON(property) + ':' + value);
                }
                return '{' + results.join(',') + '}';
                break;
            case 'array':
                var results = [];

                for (var i = 0; i < object.length; i++) {
                    var value = jQuery.toJSON(object[i]);
                    if (value !== undefined) results.push(value);
                }
                return '[' + results.join(',') + ']';
                break;
        }
    }
});


var BingoTouch = {};
//事件：页面初始化时触发
BingoTouch.init = function () { };
//事件：页面DOM载入完毕后触发
BingoTouch.ready = function () { };
//事件：页面资源载入完毕后触发
BingoTouch.onload = function () { };
//事件：页面显示时触发（包括页面静态加载、缓存等情况）
BingoTouch.display = function () { };
//事件：菜单按钮点击事件
BingoTouch.onMenu = function () { };

BingoTouch.Common = {};
BingoTouch.WebView = {};
BingoTouch.Biz = {};
BingoTouch.App = {};
BingoTouch.Local = {};
BingoTouch.Db = {};
BingoTouch.Device = {};
BingoTouch.BIS = {};
BingoTouch.Video = {};
BingoTouch.Input = {};
BingoTouch.WebCache = {};
BingoTouch.Message = {};
BingoTouch.Map = {};
BingoTouch.Grape = {};
//组件
BingoTouch.Module = {};

//----BingoTouch.WebView------------------------------------------------

// 在当前BingoWebView中装载指定的页面
BingoTouch.WebView.load = function (uri, arg, transition, isShowProgress, isRecordHistory) {
    if (uri == null) return;
    if (arg == null) arg = "";
    if (transition == null) transition = "Slideup";
    if (isShowProgress == null) isShowProgress = true;
    if (isRecordHistory == null) isRecordHistory = true;

    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.load(uri, arg, isRecordHistory, isShowProgress);
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.WebView.load", [uri, arg, transition, isShowProgress, isRecordHistory]);
    }
    if (BingoTouch.Device.isPC) {
        if (arg != null && arg != "")
            uri = uri + "?p=" + escape(arg);

        window.location.href = uri;
    }
}

// 读取当前Web页面参数
BingoTouch.WebView.getPageParameter = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getTempParm();
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.WebView.getPageParameter");
    }
    if (BingoTouch.Device.isPC) {
        var reg = new RegExp("(^|&)?p=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null)
            return unescape(r[2]);
        return null;
    }
}

// BingoWebView前进
BingoTouch.WebView.forward = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.forward();
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.WebView.forward");
    }
    if (BingoTouch.Device.isPC) {
        window.history.forward();
    }
}
// BingoWebView后退
BingoTouch.WebView.back = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.back();
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.WebView.back");
    }
    if (BingoTouch.Device.isPC) {
        window.history.back();
    }
}
// BingoWebView跳至指定的页面
BingoTouch.WebView.go = function (step) {
    if (step == null) return;
    var intStep = parseInt(step);
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.go(intStep);
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.WebView.go", [step]);
    }
    if (BingoTouch.Device.isPC) {
        if (intStep > 0) window.history.forward(intStep);
        if (intStep < 0) window.history.back(intStep);
    }
}

// BingoWebView能否前进
BingoTouch.WebView.canForward = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.canForward();
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.WebView.canForward");
    }
    if (BingoTouch.Device.isPC) {
        return false;
    }
}
// BingoWebView能否后退
BingoTouch.WebView.canBack = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.canBack();
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.WebView.canBack");
    }
    if (BingoTouch.Device.isPC) {
        return false;
    }
}
// 得到当前BingoWebView的页面地址
BingoTouch.WebView.getURI = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getURI();
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.WebView.getURI");
    }
    if (BingoTouch.Device.isPC) {
        return window.location.href;
    }
}
// 读取当前BingoWebView的浏览历史记录
BingoTouch.WebView.getHistory = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getHistory();
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.WebView.getHistory");
    }
    if (BingoTouch.Device.isPC) {
        return window.history;
    }
}
// 清除当前BingoWebView的浏览历史记录
BingoTouch.WebView.clearHistory = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.clearHistory();
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.WebView.clearHistory");
    }
    if (BingoTouch.Device.isPC) {
        BingoTouch.Common.alert("This API is not supported by PC.");
    }
}
// 重新载入当前Web页面
BingoTouch.WebView.refresh = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.refresh();
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.WebView.refresh");
    }
    if (BingoTouch.Device.isPC) {
        window.location.href = window.location.href;
    }

}
// 显示WebView的等待进度条
BingoTouch.WebView.wait = function (status, callback) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        if (status)
            window.BingoWebView.showProgressBar(BingoTouch.packFunction(callback));
        else
            window.BingoWebView.hideProgressBar();
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.WebView.wait", [status, BingoTouch.packFunction(callback)]);
    }
    if (BingoTouch.Device.isPC) {

    }
}

// 得到当前WebView的高度
BingoTouch.WebView.height = function () {
    return parseInt(window.innerHeight);
}

// 得到当前WebView的宽度
BingoTouch.WebView.width = function () {
    return parseInt(window.innerWidth);
}

//设置页面默认变焦密度
// FAR
// MEDIUM
// CLOSE
BingoTouch.WebView.setDefaultZoom = function (zoom) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.setDefaultZoom(zoom);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.WebView.setDefaultZoom", [zoom]);
    }
    if (BingoTouch.Device.isPC) {
        BingoTouch.Common.alert("This API is not supported by PC.");
    }
}

BingoTouch.WebView.showPic = function (path, size) {
    if (size == null)
        size = 0;
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.pictureBrowsing(path, size);
    }
    if (BingoTouch.Device.isIOS) {

    }
    if (BingoTouch.Device.isPC) {
        window.open(path);
    }
}
//----BingoTouch.Cache------------------------------------------------

// 设置全局的缓存模式
// 0 DEFAULT（LOAD_CACHE_ELSE_NETWORK）                                              0
//        默认值。在全局缓存开关中，默认值为LOAD_CACHE_ELSE_NETWORK
// 1 LOAD_CACHE_ELSE_NETWORK                                                                     1
//        优先加载缓存，如果无缓存，则先访问远程资源建立缓存。
// 2 LOAD_NO_CACHE                                                                                           2
//        不加载缓存，始终加载远程资源
// 3 LOAD_CACHE_ONLY                                                                                       3
//        只加载缓存，如果无缓存则直接返回远程资源地址。
BingoTouch.WebCache.setMode = function (mode) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.setBingoCacheMode(mode);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.WebCache.setMode", [mode]);
    }
    if (BingoTouch.Device.isPC) {
        BingoTouch.Common.alert("This API is not supported by PC.");
    }
}
// 读取全局的缓存模式
BingoTouch.WebCache.getMode = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getBingoCacheMode();
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.WebCache.getMode");
    }
    if (BingoTouch.Device.isPC) {
        BingoTouch.Common.alert("This API is not supported by PC.");
    }
}
// 获取Web资源的缓存版本
// 0 DEFAULT（LOAD_CACHE_ELSE_NETWORK）
//        使用全局缓存模式
// 1 LOAD_CACHE_ELSE_NETWORK
//        优先加载缓存，如果无缓存，则先访问远程资源建立缓存。
// 2 LOAD_NO_CACHE
//        不加载缓存，始终加载远程资源
// 3 LOAD_CACHE_ONLY
//        只加载缓存，如果无缓存则直接返回远程资源
BingoTouch.WebCache.get = function (url, mode, expire) {
    if (url == null || url == "") return;
    if (mode == null || mode == "") mode = 0;
    if (expire == null || expire == "") expire = 31557600;
    if (BingoTouch.App.isDebug) return url;

    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getCache(url, mode, expire);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.WebCache.get", [url, mode, expire]);
    }
    if (BingoTouch.Device.isPC) {
        BingoTouch.Common.alert("This API is not supported by PC.");
    }
}
// 查询指定的Web资源是否存在缓存
BingoTouch.WebCache.isCache = function (url) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.isCache(url);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.WebCache.isCache", [url]);
    }
    if (BingoTouch.Device.isPC) {
        BingoTouch.Common.alert("This API is not supported by PC.");
    }
}
// 移除指定的Web资源的缓存
BingoTouch.WebCache.remove = function (url, data) {
    if (url == null || url == "") return;
    if (data == null) data = "";
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.removeCache(url, data);
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.WebCache.remove", [url, data]);
    }
    if (BingoTouch.Device.isPC) {
        BingoTouch.Common.alert("This API is not supported by PC.");
    }
}
// 清空所有Web资源的缓存
BingoTouch.WebCache.clear = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.clearCache();
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.WebCache.clear");
    }
    if (BingoTouch.Device.isPC) {
        BingoTouch.Common.alert("This API is not supported by PC.");
    }
}
//----BingoTouch.Message------------------------------------------------
BingoTouch.Message.send = function (uri, message) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.sendMessage(uri, message);
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.Message.send", [uri, message]);
    }
    if (BingoTouch.Device.isPC) {
        BingoTouch.Common.alert("This API is not supported by PC.");
    }
}

// 消息接收，需要被重载
BingoTouch.Message.fire = function (event) { }


//----BingoTouch.App------------------------------------------------

// 应用是否处于Debug状态
BingoTouch.App.isDebug = true;

// 得到应用标识
BingoTouch.App.getAppId = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getAppPackage();
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.App.getAppId");
    }
    if (BingoTouch.Device.isPC) {
        return null;
    }
}

// 得到应用版本号
BingoTouch.App.getVersionCode = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getAppVersionCode();
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.App.getVersionCode");
    }
    if (BingoTouch.Device.isPC) {
        return null;
    }

}

// 得到应用版本名称
BingoTouch.App.getVersionName = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getAppVersionName();
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.App.getVersionName");
    }
    if (BingoTouch.Device.isPC) {
        return null;
    }

}

// 跳至应用默认栏目
BingoTouch.App.goMainMenu = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.goMainMenu();
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.App.goMainMenu");
    }
    if (BingoTouch.Device.isPC) {
        return null;
    }
}

// 内部方法：当前应用是否处于debug状态
BingoTouch.App.getDebugState = function () {
    if (BingoTouch.App.getAppId() == "com.bingo.mobile.debug")
        return true;
    else
        return false;
}


//应用退出
BingoTouch.App.exit = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.exitApp();
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.App.exit");
    }
    if (BingoTouch.Device.isPC) {
        window.close();
    }
}
// 移走封面页，应用开始
BingoTouch.App.start = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.removeCover();
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.App.start");
    }
    if (BingoTouch.Device.isPC) {
        return null;
    }

}

// 设置指定Menu上显示的消息数
BingoTouch.App.setMenuNotify = function (index, count) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.setMenuMessage(index, count);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.App.setMenuNotify", [index, count]);
    }
    if (BingoTouch.Device.isPC) {
        return null;
    }
}

// 设置导航栏是否可见
BingoTouch.App.setNavigatorVisible = function (isVisible) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.setNavigatorVisible(isVisible);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.App.setNavigatorVisible", [isVisible]);
    }
    if (BingoTouch.Device.isPC) {
        return null;
    }
}

// 转至BingoApp的指定栏目
BingoTouch.App.goMenu = function (mid, arg, transition, isShowProgress) {
    if (mid == null) return;
    if (transition == null) transition = "Slideup";
    if (isShowProgress == null) isShowProgress = true;

    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.goMenu(mid);
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.App.goMenu", [mid, arg, transition, isShowProgress]);
    }
    if (BingoTouch.Device.isPC) {

    }

}

// 运行指定的终端应用
BingoTouch.App.run = function (appId, main) {
    if (appId == "" && appId == null) return;
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        if (main == null)
            window.BingoWebView.startApp(appId);
        else
            window.BingoWebView.startApp(appId, main);
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.App.run", [appId, main]);
    }
    if (BingoTouch.Device.isPC) {
        BingoTouch.Common.alert("This API is not supported by PC.");
    }
}

// 判断指定的终端应用是否存在
BingoTouch.App.isExist = function (appId) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.isExistApp(appId);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.App.isExist", [appId]);
    }
    if (BingoTouch.Device.isPC) {
        BingoTouch.Common.alert("This API is not supported by PC.");
        return false;
    }
}

// 卸载指定的终端应用
BingoTouch.App.uninstall = function (appId, callBack) {
    var callBackFunName = "";
    if (callBack != null && callBack.name != null) callBackFunName = callBack.name;

    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.uninstallApplication(appId, callBackFunName);
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.Common.alert("请到系统管理中卸载此应用.");
    }
    if (BingoTouch.Device.isPC) {
        BingoTouch.Common.alert("This API is not supported by PC.");
    }
}


// 设置应用全局变量
BingoTouch.App.setGlobalVariable = function (key, value) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.setGlobalVariable(key, value);
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.App.setGlobalVariable", [key, value]);
    }
    if (BingoTouch.Device.isPC) {
        BingoTouch.Common.alert("This API is not supported by PC.");
    }
}

// 读取应用全局变量
BingoTouch.App.getGlobalVariable = function (key) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getGlobalVariable(key);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.App.getGlobalVariable", [key]);
    }
    if (BingoTouch.Device.isPC) {

    }
}

// 下载并安装应用安装包
BingoTouch.App.download = function (url, title, callback) {
    var callBackFunName = "";
    if (callback != null && callback.name != null) callBackFunName = callback.name;

    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        // 注意android版，无回调函数
        window.BingoWebView.download(url, title, title);
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.App.download", [url, title, callBackFunName]);
    }
    if (BingoTouch.Device.isPC) {
        window.location.href = url;
    }
}
// 安装应用
BingoTouch.App.install = function (uri, callback) {
    var callBackFunName = "";
    if (callback != null && callback.name != null) callBackFunName = callback.name;

    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {

    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.App.install", [url, title, callBackFunName]);
    }
    if (BingoTouch.Device.isPC) {

    }
}

//初始化框架，内部方法，自动调用。
BingoTouch.App.APIReturnValueIndex = 0;
BingoTouch.App.APIReturnValue = "ISO_API_RETURNVALUE";
BingoTouch.App.initFramework = function () {
    var agent = window.navigator.userAgent;
    if ($.isEmptyObject(agent) || agent.search("Android") > 0) {
        BingoTouch.Device.isAndroid = true;
        if (window.BingoWebView.getAndroidVersion()>=13) {
            var viewport = 'user-scalable=no,target-densitydpi=240,width=480';
            if ($("meta[name='viewport']").length > 0) {
                $("meta[name='viewport']").attr("content", viewport);
            } else {
                var element = document.createElement('meta');
                element.name = "viewport";
                element.content = viewport;
                var head = document.getElementsByTagName('head')[0];
                head.appendChild(element);
            }
        }
    } else
        if (agent.search("iPad") > 0 || agent.search("iPhone") > 0 || agent.search("iPod") > 0) {
            BingoTouch.Device.isIOS = true;

            // 初始化iOS API接口通道	
            BingoTouch.runIOS = function (method, arg) {

                if (method == null || method == "") return;
                method = method.replace(/\./g, '_');
                if (arg == null) arg = "";

                //                var json_arg = '{"arg":[', t;
                //                for (var i = 0; i < arg.length; i++) {
                //                    if (arg[i] == null) arg[i] = "";
                //                    t = typeof (arg[i]);
                //                    if (t == "number" || t == "object" || t == "boolean") {
                //                        json_arg += arg[i];
                //                    } else { json_arg += '"' + arg[i].replace(/\"/g, "/u0022") + '"'; }
                //                    if (i + 1 < arg.length) json_arg += ",";
                //                }
                //                json_arg += "]}";
                var json_arg = jQuery.toJSON({
                    arg: arg
                });
                // 	alert(json_arg);
                var vid = BingoTouch.App.APIReturnValue + BingoTouch.App.APIReturnValueIndex;
                eval(vid + "=null");

                var iOSFrame = document.createElement("IFRAME");
                iOSFrame.style.display = 'none';

                iOSFrame.setAttribute("src", "bingotouch://" + method + ":" + vid + ":" + encodeURIComponent(json_arg));

                document.documentElement.appendChild(iOSFrame);
                iOSFrame.parentNode.removeChild(iOSFrame);

                var result = eval(vid);
                eval(vid + "=null");
                BingoTouch.App.APIReturnValueIndex++;

                iOSFrame = null;
                return result;
            }
            // 初始化Web页面的缩放
            var viewport = 'width=' + BingoTouch.Device.width() + ',user-scalable=no';
            if ($("meta[name='viewport']").length > 0) {
                $("meta[name='viewport']").attr("content", viewport);
            } else {
                var element = document.createElement('meta');
                element.name = "viewport";
                element.content = viewport;
                var head = document.getElementsByTagName('head')[0];
                head.appendChild(element);
            }

        } else { BingoTouch.Device.isPC = true; }

    BingoTouch.App.isDebug = BingoTouch.App.getDebugState();
    BingoTouch.packFunction = function (func) {
        if (func != null && typeof (func) == 'function') {
            var funName = "_bingTouchCallback" + parseInt(Math.random() * 99999999 + 1);
            window[funName] = function () {
                func.apply(this, arguments);
            };
            return funName;
        }
        return "";
    }
}

//----BingoTouch.Local------------------------------------------------

// 将远程文件保存为本地文件
BingoTouch.Local.saveWebFile = function (url, path, fileName, isOverride) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.saveLocalFile(url, path, fileName, isOverride);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Local.saveWebFile", [url, path, fileName, isOverride]);
    }
    if (BingoTouch.Device.isPC) {
        BingoTouch.Common.alert("This API is not supported by PC.");
    }
}

// 判断本地文件是否存在 
BingoTouch.Local.isExistFile = function (path) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.isExistLocalFile(path);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Local.isExistFile", [path]);
    }
    if (BingoTouch.Device.isPC) {
        BingoTouch.Common.alert("This API is not supported by PC.");
    }
}

// 得到文件的实际存储路径（Web页面中可访问） 
BingoTouch.Local.getLocalFilePath = function (path) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getLocalFilePath(path);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Local.getLocalFilePath", [path]);
    }
    if (BingoTouch.Device.isPC) {

    }
}


// 在指定id的Hashmap文件中保存指定key的value
BingoTouch.Local.saveHashmap = function (id, key, value) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.setLocalVariable(id, key, value);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Local.saveHashmap", [id, key, value]);
    }
    if (BingoTouch.Device.isPC) {

    }
}
// 读取指定id的Hashmap文件中指定key的value
BingoTouch.Local.readHashmap = function (id, key) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getLocalVariable(id, key);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Local.readHashmap", [id, key]);
    }
    if (BingoTouch.Device.isPC) {

    }
}

// 读取指定id的Hashmap文件中所有的value
BingoTouch.Local.readHashmapValues = function (id) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getLocalVariableValues(id);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Local.readHashmapValues", [id]);
    }
    if (BingoTouch.Device.isPC) {

    }
}
// 读取指定id的Hashmap文件中所有的key
BingoTouch.Local.readHashmapKeys = function (id) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getLocalVariableKeys(id);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Local.readHashmapKeys", [id]);
    }
    if (BingoTouch.Device.isPC) {

    }
}

// 清空指定id的Hashmap文件
BingoTouch.Local.clearHashmap = function (id) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.clearLocalVariable(id);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Local.clearHashmap", [id]);
    }
    if (BingoTouch.Device.isPC) {

    }
}
// 删除指定的Hashmap文件中指定Key的数据项
BingoTouch.Local.removeHashmap = function (id, key) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.removeLocalVariable(id, key);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Local.removeHashmap", [id, key]);
    }
    if (BingoTouch.Device.isPC) {

    }
}

// 选择设备本地文件
BingoTouch.Local.localFileSelector = function (callback) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.localFileSelector(BingoTouch.packFunction(callback));
    }
    if (BingoTouch.Device.isIOS) {

    }
    if (BingoTouch.Device.isPC) {

    }
}

// 返回本地图像的Base64编码格式 
BingoTouch.Local.getBase64String = function (path) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getImageProcessing(path);
    }
    if (BingoTouch.Device.isIOS) { }
    if (BingoTouch.Device.isPC) { }
}

BingoTouch.Local.localImageSelector = function (callback) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.selectFile(['camera', 'image'], BingoTouch.packFunction(callback));
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch_Local_selectFile", [{ filter: ['camera', 'image'] }, BingoTouch.packFunction(callback)]);
    }
    if (BingoTouch.Device.isPC) { }
}
//----BingoTouch.Common------------------------------------------------

// 提示对话框
BingoTouch.Common.alert = function (txt) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        alert(txt);
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.Common.alert", [txt]);
    }
    if (BingoTouch.Device.isPC) {

    }
}

// 临时提示框
BingoTouch.Common.toast = function (txt) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.bingoToast(txt);
    }
    if (BingoTouch.Device.isIOS) {

    }
    if (BingoTouch.Device.isPC) {

    }
}

// 获取设备信息：imsi,imei,iccid,mobile(号码),model(型号),os(操作系统)
BingoTouch.Common.getDeviceInfo = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return jQuery.evalJSON(window.BingoWebView.getDeviceInfo());
    }
    if (BingoTouch.Device.isIOS) {

    }
    if (BingoTouch.Device.isPC) {

    }
}

// 确认对话框
BingoTouch.Common.confirm = function (txt) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return confirm(txt);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Common.confirm", [txt]);
    }
    if (BingoTouch.Device.isPC) {

    }
}

// 为iOS增加的临时方法
BingoTouch.Common.getAppSettings = function (scriptId, key) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {

    }
    if (BingoTouch.Device.isIOS) {
        var p = { "scriptId": scriptId, "key": key };
        window.location.href = "bingotouch://getAppSettings[BingoTouch.Common.WAITFLAG]?p=" + BingoTouch.Common.json2string(p);
        BingoTouch.Common.wait();
    }
    if (BingoTouch.Device.isPC) {

    }

}

// 将JSON对象转换成字符串
BingoTouch.Common.json2string = function (json) {
    return JSON.stringify(json);
}
// 将字符串转换成JSON对象
BingoTouch.Common.string2json = function (str) {
    return JSON.parse(str);
}

// HTML编码
BingoTouch.Common.htmlEncode = function (txt) {
    txt = txt.replace(/&/g, '&amp').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    var regExp = new RegExp(" ", "g")
    txt = txt.replace(regExp, "&nbsp;");
    regExp = new RegExp("\n", "g")
    txt = txt.replace(regExp, "<br>");
    return txt;
}

// 发送Web请求
BingoTouch.Common.WebRequest = function (url, type, contentType, data, async, onGetCompleted, onError, cachemode, expires, headers) {
    if (url == null || url == "") return;
    if (onGetCompleted == null || onGetCompleted == "") return;
    if (onError == null || onError == "") onError = BingoTouch_RequestError;
    if (type == null || type == "") type = "GET";
    if (contentType == null || contentType == "") contentType = "text/html";
    if (async == null || async == "") async = false;
    if (cachemode == null || cachemode.toString() == "") cachemode = 2;
    if (headers == null) headers = "";
    if (expires == null || expires.toString() == "") expires = 31557600;
	if (data == null) data = "";
    if (typeof (data) == 'object') data = jQuery.toJSON(data);

    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        var p = { type: type, contentType: contentType, url: url, data: data, success: BingoTouch.packFunction(onGetCompleted), async: async, error: BingoTouch.packFunction(onError), cachemode: cachemode, expires: expires, header: headers };
        window.BingoWebView.sendHttpRequest(jQuery.toJSON(p));
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Common.WebRequest", [url, type, contentType, data, async, BingoTouch.packFunction(onGetCompleted), BingoTouch.packFunction(onError), cachemode, expires, headers]);
    }
    if (BingoTouch.Device.isPC) {
        $.ajax({ type: type, contentType: contentType, url: url, data: data, success: onGetCompleted, async: async, error: onError });
    }
}
// 通信失败处理
function BingoTouch_RequestError(r) {
    BingoTouch.Common.alert('通信失败：' + r.status);
    BingoTouch.WebView.wait(false);
}

BingoTouch.Common.getDataByDMS = function (url, CommandName, Params, onGetCompleted, async) {
    $.ajax({
        type: "POST",
        contentType: "text/x-json;charset=UTF-8",
        url: url,
        dataType: "text",
        data: "{CommandName:'" + CommandName + "',Params:" + Params + "}",
        success: onGetCompleted,
        async: async,
        error: function (result) {
            alert("数据获取失败:" + result.statusText);
        }
    });
}


/*--------BingoTouch.SSO----------------------*/
BingoTouch.SSO = {};
/*sso登录接口
param:{
type,userName,password,get_spec_secret,get_service_ticket
}
*/
BingoTouch.SSO.Login = function (type, param, successCallback, failCallback) {
    if (type == null || type == "") return;
    if (param.userName == null || param.userName == "") return;
    if (param.password == null || param.password == "") return;
    if (successCallback == null || successCallback == "") return;
    if (failCallback == null || failCallback == "") { failCallback = BingoTouch_RequestError; }
    var get_spec_secret = false || param.get_spec_secret;
    var get_service_ticket = false || param.get_service_ticket;
    var credential = {
        USERNAME: param.userName,
        PASSWORD: param.password,
        get_spec_secret: get_spec_secret,
        get_service_ticket: get_service_ticket
    };
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.ssoLogin(type, jQuery.toJSON(credential), BingoTouch.packFunction(successCallback), BingoTouch.packFunction(failCallback));
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.BingoSoftAPI.SSO.Login", [type, credential, BingoTouch.packFunction(successCallback), BingoTouch.packFunction(failCallback)]);
    }
}
/*sso注销接口*/
BingoTouch.SSO.Logout = function (params) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.ssoLogin(jQuery.toJSON(params));
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.BingoSoftAPI.SSO.Logout", [params]);
    }
}
/*刷新token*/
BingoTouch.SSO.RefreshToken = function (params, successCallback, failCallback) {
    if (params == null || params == "") return;
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.ssoRefreshToken(jQuery.toJSON(params), BingoTouch.packFunction(successCallback), BingoTouch.packFunction(failCallback));
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.BingoSoftAPI.SSO.RefreshToken", [params, BingoTouch.packFunction(successCallback), BingoTouch.packFunction(failCallback)]);
    }
}
/*获取loginTicket*/
BingoTouch.SSO.LoginTicket = function (params, successCallback, failCallback) {
    if (params == null || params == "") return;
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.ssoLoginTicket(jQuery.toJSON(params), BingoTouch.packFunction(successCallback), BingoTouch.packFunction(failCallback));
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.BingoSoftAPI.SSO.LoginTicket", [params, BingoTouch.packFunction(successCallback), BingoTouch.packFunction(failCallback)]);
    }
}
/*获取ServiceTicket*/
BingoTouch.SSO.ServiceTicket = function (params, successCallback, failCallback) {
    if (params == null || params == "") return;
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.ssoServiceTicket(jQuery.toJSON(params), BingoTouch.packFunction(successCallback), BingoTouch.packFunction(failCallback));
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.BingoSoftAPI.SSO.ServiceTicket", [params, BingoTouch.packFunction(successCallback), BingoTouch.packFunction(failCallback)]);
    }
}
/*-------- End BingoTouch.SSO------------------*/

/*eim接口*/
BingoTouch.EIM = {};
BingoTouch.EIM.GetDeptInfos = function (userId, successCallback, failCallback) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.eim_GetDeptInfos(userId, BingoTouch.packFunction(successCallback), BingoTouch.packFunction(failCallback));
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch_BingoSoftAPI_EIM_getDeptInfos", [userId, BingoTouch.packFunction(successCallback), BingoTouch.packFunction(failCallback)]);
    }
}

BingoTouch.EIM.GetDeptInfos_Sort = function (userId, sortField, type, successCallback, failCallback) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.eim_GetDeptInfos_Sort(userId, sortField, type, BingoTouch.packFunction(successCallback), BingoTouch.packFunction(failCallback));
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch_BingoSoftAPI_EIM_getDeptInfos_Sort", [userId, sortField, type, BingoTouch.packFunction(successCallback), BingoTouch.packFunction(failCallback)]);
    }
}

BingoTouch.EIM.GetUserInfoByDeptID = function (userId, successCallback, failCallback) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.eim_GetUserInfoByDeptID(userId, BingoTouch.packFunction(successCallback), BingoTouch.packFunction(failCallback));
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch_BingoSoftAPI_EIM_getUserInfoByDeptID", [userId, BingoTouch.packFunction(successCallback), BingoTouch.packFunction(failCallback)]);
    }
}

BingoTouch.EIM.GetUserInfoByDeptName = function (deptName, successCallback, failCallback) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.eim_GetUserInfoByDeptName(deptName, BingoTouch.packFunction(successCallback), BingoTouch.packFunction(failCallback));
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch_BingoSoftAPI_EIM_getUserInfoByDeptName", [deptName, BingoTouch.packFunction(successCallback), BingoTouch.packFunction(failCallback)]);
    }
}

BingoTouch.EIM.GetUserInfos = function (userId, successCallback, failCallback) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.eim_GetUserInfos(userId, BingoTouch.packFunction(successCallback), BingoTouch.packFunction(failCallback));
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch_BingoSoftAPI_EIM_getUserInfos", [userId, BingoTouch.packFunction(successCallback), BingoTouch.packFunction(failCallback)]);
    }
}
/*-------- End BingoTouch.EIM------------------*/

// 提醒
BingoTouch.Common.notify = function (tip, title, content) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.showNotification(tip, title, content);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Common.notify", [tip, title, content]);
    }
    if (BingoTouch.Device.isPC) {
        BingoTouch.Common.alert(tip + "\n\r" + title + ":" + content);
    }
}

// 网络是否连通
BingoTouch.Common.isNetworkConnected = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.isNetworkConnected();
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Common.isNetworkConnected");
    }
    if (BingoTouch.Device.isPC) {

    }
}

// 获取当前网络类型
BingoTouch.Common.getActiveNetwork = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getActiveNetwork();
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Common.getActiveNetwork");
    }
    if (BingoTouch.Device.isPC) {

    }
}

// 获取当前网络状态
// CONNECTED 已连接
// CONNECTIONG 正在连接
// DISCONNETED 已断开
// DISCONNETING 正在断开
// SUSPENDED 已挂起
// UNKNOW 未知
BingoTouch.Common.getActiveNetworkStatus = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getActiveNetworkStatus();
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Common.getActiveNetworkStatus");
    }
    if (BingoTouch.Device.isPC) {

    }
}

// 设置网络状态变化时的回调函数
BingoTouch.Common.setNetworkChangeCallback = function (fun) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.setNetworkChangeCallback(BingoTouch.packFunction(fun));
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Common.setNetworkChangeCallback", [BingoTouch.packFunction(fun)]);
    }
    if (BingoTouch.Device.isPC) {

    }
}

// 设置定时提醒服务
// 远程数据格式：{"notification":{"tip":"","title":"","content":""},"globalVar":[{id:"",value:0}]}
// 固定以Post方式，发送Web请求
BingoTouch.Common.startNotifactionService = function (id, url, action, data, period) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.startNotifactionTimer(id, url, action, data, period);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Common.startNotifactionService", [id, url, action, data, period]);
    }
    if (BingoTouch.Device.isPC) {

    }
}

// 关闭定时提醒服务
BingoTouch.Common.stopNotifactionService = function (id) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.stopNotifactionTimer(id);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Common.stopNotifactionService", [id]);
    }
    if (BingoTouch.Device.isPC) {

    }
}


//----BingoTouch.Db------------------------------------------------
//执行sql
BingoTouch.Db.execSQL = function (sql) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return jQuery.evalJSON(window.BingoWebView.execSQL(sql));
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Db.execSQL", [sql]);
    }
    if (BingoTouch.Device.isPC) {
    }
}

//查询数据
BingoTouch.Db.sqlQuery = function (sql) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return jQuery.evalJSON(window.BingoWebView.sqlQuery(sql));
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Db.sqlQuery", [sql]);
    }
    if (BingoTouch.Device.isPC) {
    }
}


//----BingoTouch.Device------------------------------------------------


BingoTouch.Device.isAndroid = false;
BingoTouch.Device.isIOS = false;
BingoTouch.Device.isPC = false;

// 得到设备显示密度
//	DENSITY_LOW = 120;
//	DENSITY_MEDIUM = 160;
//	DENSITY_HIGH = 240;
BingoTouch.Device.DPI = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getDisplayDensityDpi();
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Device.DPI");
    }
    if (BingoTouch.Device.isPC) {
        return window.screen.pixelDepth;
    }
}

// 得到设备屏幕宽度
BingoTouch.Device.width = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return parseInt(window.BingoWebView.getDisplayWidth());
    }
    if (BingoTouch.Device.isIOS) {
        return parseInt(BingoTouch.runIOS("BingoTouch.Device.width"));
    }
    if (BingoTouch.Device.isPC) {
        return parseInt(window.screen.availWidth);
    }
}
// 得到设备屏幕高度
BingoTouch.Device.height = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return parseInt(window.BingoWebView.getDisplayHeight());
    }
    if (BingoTouch.Device.isIOS) {
        return parseInt(BingoTouch.runIOS("BingoTouch.Device.height"));
    }
    if (BingoTouch.Device.isPC) {
        return parseInt(window.screen.availHeight);
    }
}
// 进行条码扫描
BingoTouch.Device.getBarcode = function (callBack) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.getBarcode(BingoTouch.packFunction(callBack));
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.Device.getBarcode", [BingoTouch.packFunction(callBack)]);
    }
    if (BingoTouch.Device.isPC) { BingoTouch.Common.alert("This API is not supported by PC."); }
}
// 拍照,callback函数中接受照片路径
BingoTouch.Device.getPhoto = function (callBack) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.photograph(BingoTouch.packFunction(callBack));
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.Device.getPhoto", [BingoTouch.packFunction(callBack)]);
    }
    if (BingoTouch.Device.isPC) { BingoTouch.Common.alert("This API is not supported by PC."); }
}

// 拨电话
BingoTouch.Device.call = function (tel, callBack) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.dialCall(tel, BingoTouch.packFunction(callBack));
    }
    if (BingoTouch.Device.isIOS) {

    }
    if (BingoTouch.Device.isPC) { BingoTouch.Common.alert("This API is not supported by PC."); }
}

BingoTouch.Device.setKeyDownCallback = function (callBack) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.setKeyDownCallback(BingoTouch.packFunction(callBack));
    }
    if (BingoTouch.Device.isIOS) {

    }
    if (BingoTouch.Device.isPC) { BingoTouch.Common.alert("This API is not supported by PC."); }
}

BingoTouch.Device.startRfid = function (distanceMillisecond, callback) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.startRfid(distanceMillisecond, BingoTouch.packFunction(callback));
    }
    if (BingoTouch.Device.isIOS) {
    }
    if (BingoTouch.Device.isPC) {
    }
}

BingoTouch.Device.stopRfid = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.stopRfid();
    }
    if (BingoTouch.Device.isIOS) {
    }
    if (BingoTouch.Device.isPC) {
    }
}

BingoTouch.Device.drawBoard = function (bgColor, foreColor, foreSize, successCallback, cancelCallback) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.drawBoard(bgColor, foreColor, foreSize, BingoTouch.packFunction(successCallback), BingoTouch.packFunction(cancelCallback));
    }
    if (BingoTouch.Device.isIOS) {
    }
    if (BingoTouch.Device.isPC) {
    }
}

//----BingoTouch.Video------------------------------------------------

// 播放远程或本地视频
BingoTouch.Video.play = function (uri) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.startMediaPlayer(uri);
    }
    if (BingoTouch.Device.isIOS) {
        return BingoTouch.runIOS("BingoTouch.Video.play", [uri]);
    }
    if (BingoTouch.Device.isPC) { }
}

//----BingoTouch.Input------------------------------------------------

// BTDate控件点击处理
BingoTouch.Input.selectDate = function () {
    var dateDiv = event.srcElement.parentElement;

    var id = dateDiv.id;
    var value = dateDiv.attributes["value"].nodeValue;
    var data = dateDiv.attributes["data"].nodeValue;
    var callback = "BingoTouch.Input.dateSelected";
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.showDate(id, value, data, callback);
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.Input.selectDate", [id, value, data, callback]);
    }
    if (BingoTouch.Device.isPC) {
        showPCDateSelect(id, value, data, callback);
    }
}
// 设置BTSelect控件的选中项
BingoTouch.Input.setDate = function (date) {
    if (date != null && date != "") {
        BingoTouch.Input.dateSelected(this.id, date);
    }
}
// BTDate控件选中后事件
BingoTouch.Input.dateSelected = function (id, value) {
    if (value != null && $("#" + id).length > 0) {
        var curV = $("#" + id).attr("value");

        $("#" + id).children("span").html(value);
        $("#" + id).attr("value", value);

        // 触发onChange事件
        if (curV != value) {
            var f = $("#" + id).attr("onChange");
            if (f != null && f != "") eval(f);
        }
    }
}

// BTSelect控件点击处理
BingoTouch.Input.select = function () {
    var selectDiv = event.srcElement.parentElement;
    var id = selectDiv.id;
    var selectedIndex = selectDiv.attributes["selectedIndex"].nodeValue;
    var data = selectDiv.attributes["data"].nodeValue;
    var callback = "BingoTouch.Input.selected";
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        window.BingoWebView.showSelect(id, selectedIndex, data, callback);
    }
    if (BingoTouch.Device.isIOS) {
        BingoTouch.runIOS("BingoTouch.Input.select", [id, selectedIndex, data, callback]);
    }
    if (BingoTouch.Device.isPC) {
        showPCSelect(id, selectedIndex, data, callback);
    }
}
// 设置BTSelect控件的选中项
BingoTouch.Input.setSelectedIndex = function (index) {
    aryIndex = String(index).split(",");

    var json = BingoTouch.Common.string2json(this.attributes["data"].nodeValue);
    // 一维选择处理
    if (aryIndex.length == 1) {
        index = parseInt(index);
        if (json.data[index] != null) {
            BingoTouch.Input.selected(this.id, index, json.data[index]);
        }
    }
    // 二维选择处理
    if (aryIndex.length == 2) {
        var option1 = json.data[parseInt(aryIndex[0])];
        if (option1 != null && option1.data != null) {
            var option2 = option1.data[parseInt(aryIndex[1])];
            if (option2 != null)
                BingoTouch.Input.selected(this.id, index, option2);
        }
    }
}
// BTSelect控件选中后事件
BingoTouch.Input.selected = function (id, selectedIndex, data) {
    if (data != null && $("#" + id).length > 0) {
        var curV = $("#" + id).attr("value");

        $("#" + id).children("span").html(data.text);
        $("#" + id).attr("value", data.value);
        $("#" + id).attr("selectedIndex", selectedIndex);

        // 触发onChange事件
        if (curV != data.value) {
            var f = $("#" + id).attr("onChange");
            if (f != null && f != "") eval(f);
        }
    }
}
// 设置BTCheck控件的值
BingoTouch.Input.setCheckValue = function (value) {
    if (value == null) {
        if (this.value == 0)
            this.value = 1;
        else
            this.value = 0;
    } else {
        value = parseInt(value);
        this.value = value;
    }

    if (this.value == 0) {
        this.className = "BTCheck_OFF";
    } else {
        this.className = "BTCheck_ON";
    }
} // 设置BTRadio控件的值
BingoTouch.Input.setRadioValue = function (value) {
    var name = $(this).attr('name');
    if (value == null) {
        if (this.value == 0) {

            this.value = 1;
            var others = $('div[data-role="BTRadio"][name="' + name + '"]');

            for (var i = 0; i < others.length; i++) {
                others[i].setRadioValue = BingoTouch.Input.setRadioValue;
                others[i].setRadioValue(0);
            }
            this.setRadioValue(1);
        } else {
            return false;
        }
    } else {
        value = parseInt(value);
        this.value = value;
    }

    if (this.value == 0) {
        this.className = "BTCheck_OFF";
    } else {
        this.className = "BTCheck_ON";
    }
}
// 设置BTSwitch控件的值
BingoTouch.Input.setSwitchValue = function (value) {
    if ($(this).trigger('beforeSwitch') == true) {
        return;
    }
    if (value == null) {
        if (this.value == 0)
            this.value = 1;
        else
            this.value = 0;
    } else {
        value = parseInt(value);
        this.value = value;
    }

    if (this.value == 0) {
        this.className = "BTCheck_OFF";
    } else {
        this.className = "BTCheck_ON";
    }
    $(this).trigger('afterSwitch');
}
//----BingoTouch.Map------------------------------------------------
// 初始化地图
// jsondata是json对象，参数格式：[{"lo":经度,"la":纬度,title:"品高软件",content:"电话：02088888888|地址：广州市","icon":1/2/3,"data":自定义数据},{"lo":20,"la":30,title:"",content:"","icon":1,"data":{id:1}}]
// callback参数:自定义数据，经度，纬度
BingoTouch.Map.initMap = function (jsondata, longitude, latitude, callBack) {
    var callBackFunName = "";
    if (callBack != null && callBack.name != null) callBackFunName = callBack.name;

    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getBaiduMap(BingoTouch.Common.json2string(jsondata), longitude, latitude, callBackFunName);
    }
    if (BingoTouch.Device.isIOS) {

    }
    if (BingoTouch.Device.isPC) {

    }
}

// 得到当前地理位置
BingoTouch.Map.getLocation = function (callBack) {
    var callBackFunName = "";
    if (callBack != null && callBack.name != null) callBackFunName = callBack.name;

    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.getCurrentLogLat(callBackFunName);
    }
    if (BingoTouch.Device.isIOS) {

    }
    if (BingoTouch.Device.isPC) {

    }
}
//----BingoTouch.Grape------------------------------------------------
//中国移动，葡萄园组件
//用户注册
BingoTouch.Grape.register = function (username, callBack) {
    var callBackFunName = "";
    if (callBack != null && callBack.name != null) callBackFunName = callBack.name;

    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.register(username, callBackFunName);
    }
}
//显示聚合工具
BingoTouch.Grape.showUIComponent = function (pageCode, pageContent) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.showUIComponent(pageCode, pageContent);
    }
}
//隐藏聚合工具
BingoTouch.Grape.hideUIComponet = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.hideUIComponet();
    }
}


//----BingoTouch.BIS------------------------------------------------

// 中国移动BIStore：登录验证
BingoTouch.BIS.login = function (user, password) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.BISLogin(user, password);
    }
    if (BingoTouch.Device.isIOS) {

    }
    if (BingoTouch.Device.isPC) {

    }
}
// 中国移动BIStore：设置应用基本信息
BingoTouch.BIS.setClient = function (address, appId, appSecret) {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.setBISClient(address, appId, appSecret);
    }
    if (BingoTouch.Device.isIOS) {

    }
    if (BingoTouch.Device.isPC) {

    }
}

// 中国移动BIStore：注销登录
BingoTouch.BIS.logout = function () {
    if (BingoTouch.Device.isAndroid && window.BingoWebView != null) {
        return window.BingoWebView.logout();
    }
    if (BingoTouch.Device.isIOS) {

    }
    if (BingoTouch.Device.isPC) {

    }
}

//----BingoTouch初始化------------------------------------------------

$(document).bind("pagebeforecreate", function () {
    BingoTouch.App.initFramework();

    BingoTouch.Module.Form = {
        init: function () {
            this.button();
            this.buttonGroup();
            this.checkbox();
            this.radio();
            this.switchSlide();
            this.select();
        },
        button: function () {
            /* 每个按钮有的图标跟图标位置属性，图标可以是class也可以是路径
            [data-role=BTButton] 跟 class=btn 
            两种按钮表现形式相同，默认有点击高亮效果，如果不要高亮，设置mousedown btn-active
            */

            $('*[data-role=BTButton],.btn').each(function () {
                var status = $(this).attr('status');
                if (status != 1) {
                    $(this).wrapInner('<span class="btn-text"/>');

                    var icon = $(this).attr('data-icon'); //图标class或图片路径		
                    var dir = $(this).attr('icon-dir'); //图标方向
                    var url = $(this).attr('data-url'); //跳转地址
                    var urlArg = $(this).attr('url-arg'); //跳转地址带参数
                    var mousedown = $(this).attr('mousedown'); //是否取消点击高亮
                    var mouseup = $(this).attr('mouseup'); //是否取消点击高亮
                    var disabled = $(this).attr('disabled'); //是否取消点击高亮

                    //是否有图标
                    if (icon != null) {
                        if (icon.indexOf('/') > -1) {
                            $(this).append('<span class="icon"><img src="' + icon + '" alt=""/></span>');
                        } else {
                            $(this).append('<span class="icon ' + icon + '"></span>');
                        }
                    }
                    //图标在文本的哪个方向		
                    if (dir != null) {
                        if (dir == 'left') {
                            $(this).addClass('btn-icon-left');
                        } else if (dir == 'right') {
                            $(this).addClass('btn-icon-right');
                        } else if (dir == 'top') {
                            $(this).addClass('btn-icon-top');
                        } else if (dir == 'bottom') {
                            $(this).addClass('btn-icon-bottom');
                        }
                    }
                    //如果按钮有这个属性，则去掉跳转跟高亮等属性
                    if (disabled == 'true' || disabled == 'disabled') {

                    } else {
                        //是否跳转
                        if (url != null && urlArg != null) {
                            $(this).tap(function (e) {
                                BingoTouch.WebView.load(url, urlArg);
                                e.stopPropagation();
                            })
                        } else {
                            $(this).tap(function (e) {
                                BingoTouch.WebView.load(url);
                                e.stopPropagation();
                            })
                        }
                        //如果 mousedown=false 就取消默认点击高亮事件
                        if (mousedown == null || mousedown != 'false') {
                            $(this).bind('touchstart', function () {
                                $(this).addClass('btn-active');
                            })
                        }
                        //如果 mouseup=false 就默认点击高亮
                        if (mouseup == null || mouseup != 'false') {
                            $(this).bind('touchend', function () {
                                $(this).removeClass('btn-active');
                            })
                        }
                        $(this).attr('status', 1);
                    }
                }
            });
        },
        buttonGroup: function () {
            //btn-group	
            $('div[data-role="BTSwitchs"] [data-role=BTButton]').each(function () {
                $(this).tap(function (e) {
                    $(this).siblings().removeClass('btn-active');
                    e.stopPropagation();
                });
            })
        },
        checkbox: function () {
            // 初始化BTCheck控件
            if ($('div[data-role=BTCheck]').length > 0) {
                for (var i = 0; i < $('div[data-role=BTCheck]').length; i++) {
                    var classname = $('div[data-role=BTCheck]')[i].className;
                    $('div[data-role=BTCheck]')[i].setCheckValue = BingoTouch.Input.setCheckValue;

                    if (classname == "BTCheck_ON") {
                        $('div[data-role=BTCheck]')[i].setCheckValue(1);
                    } else {
                        $('div[data-role=BTCheck]')[i].setCheckValue(0);
                    }
                }
                $('div[data-role=BTCheck]').tap(function (e) {
                    this.setCheckValue();
                });
            }
        },
        radio: function () {
            // 初始化BTRadio控件

            if ($('div[data-role=BTRadio]').length > 0) {
                for (var i = 0; i < $('div[data-role=BTRadio]').length; i++) {
                    var classname = $('div[data-role=BTRadio]')[i].className;

                    $('div[data-role=BTRadio]')[i].setRadioValue = BingoTouch.Input.setRadioValue;

                    if (classname == "BTCheck_ON") {
                        $('div[data-role=BTRadio]')[i].setRadioValue(1);
                    } else {
                        $('div[data-role=BTRadio]')[i].setRadioValue(0);
                    }

                }
                $('div[data-role=BTRadio]').tap(function (e) {
                    this.setRadioValue();
                });
            }
        },
        switchSlide: function () {
            // 初始化BTSwitch控件
            if ($('div[data-role=BTSwitch]').length > 0) {
                for (var i = 0; i < $('div[data-role=BTSwitch]').length; i++) {
                    var classname = $('div[data-role=BTSwitch]')[i].className;
                    $('div[data-role=BTSwitch]')[i].setSwitchValue = BingoTouch.Input.setSwitchValue;
                    if (classname == "BTCheck_ON") {
                        $('div[data-role=BTSwitch]')[i].setSwitchValue(1);
                    } else {
                        $('div[data-role=BTSwitch]')[i].setSwitchValue(0);
                    }
                }
                $('div[data-role=BTSwitch]').tap(function (e) {
                    this.setSwitchValue();
                });
            }
        },
        select: function () {
            // 初始化BTSelect控件
            if ($('div[data-role=BTSelect]').length > 0) {
                for (var i = 0; i < $('div[data-role=BTSelect]').length; i++) {
                    $('div[data-role=BTSelect]')[i].setSelectedIndex = BingoTouch.Input.setSelectedIndex;
                }
                $('div[data-role=BTSelect]').children('span').tap(BingoTouch.Input.select);

            }
            // 初始化BTDate控件
            if ($('div[data-role=BTDate]').length > 0) {
                for (var i = 0; i < $('div[data-role=BTDate]').length; i++) {
                    var value = $('div[data-role=BTDate]')[i].getAttribute("value");
                    $('div[data-role=BTDate]')[i].setDate = BingoTouch.Input.setDate;

                    $('div[data-role=BTDate]')[i].setDate(value);

                }

                $('div[data-role=BTDate]').children('span').tap(BingoTouch.Input.selectDate);
            }
            //每个select date 的点击效果
            $('div[data-role="BTSelect"],div[data-role="BTSelectCustom"],div[data-role="BTDate"]').each(function () {
                $(this).bind('touchstart', function () {
                    $(this).addClass('btn-active');
                }).bind('touchend', function () {
                    $(this).removeClass('btn-active');
                })
            });
        }
    };
    BingoTouch.Module.List = {
        init: function () {
            this.view();
            this.checkbox();
            this.radio();
        },
        view: function () {
            //list-view
            $('.list-view li > [data-role=BTButton]').tap(function (e) {
                $(this).parent().siblings()
					.find('[data-role=BTButton]').removeClass('btn-active');
                //e.stopPropagation();
            })
        },
        checkbox: function () {
            $('.list-checkbox li > [data-role=BTButton]').tap(function (e) {
                $(this).find('>.BTCheck').toggleClass('BTCheck_ON');
                //e.stopPropagation();
            })
        },
        radio: function () {
            $('.list-radio li > [data-role=BTButton]').tap(function (e) {
                $(this).find('>.BTCheck').addClass('BTCheck_ON');
                $(this).parent().siblings()
					.find('.BTCheck').removeClass('BTCheck_ON');
                //e.stopPropagation();
            })
        }
    };
    BingoTouch.Module.Navbar = {
        init: function () {
            this.menu();
        },
        menu: function () {
            //navbar
            $('.navbar li > [data-role=BTButton],.navbar td > [data-role=BTButton]').tap(function (e) {
                $(this).parent().siblings()
					.find('[data-role=BTButton]').removeClass('btn-active');
                e.stopPropagation();
            });
            $('.navbar ul[sonmenu=true]').each(function () {
                var sonmenu = $(this).attr('sonmenu');
                var animated = $(this).attr('animate');
                //有下拉菜单时，动态添加三角形图标,默认隐藏

                $(this).find('ul').hide()
						.prev().append('<span class="angle"></span>');
                $(this).find('.angle').hide();
                //一级菜单点击
                $(this).find('[data-role="BTButton"]').not('.sonmenu [data-role="BTButton"]')
							.each(function () {
							    $(this).tap(function (e) {
							        $(this).find('.angle').show().end()
										.next().show();
							        $(this).parent().siblings()
											.find('.angle').hide().end()
												.find('ul.sonmenu').hide();

							        e.stopPropagation();
							    })
							})
                //二级菜单点击			
                $(this).find('.sonmenu [data-role="BTButton"]').tap(function (e) {
                    $(this).parent().parent().hide()
							.prev().find('.angle').hide();
                    e.stopPropagation();
                })
            });
            $('body').tap(function () {
                $('.sonmenu').hide().prev().find('.angle').hide();
            });
        }
    }
    BingoTouch.Module.Collapse = {
        init: function () {
            this.blockCollapse();
            this.listCollapse();
        },
        blockCollapse: function () {
            //collapse的点击事件
            $('.collapse-header > [data-role=BTButton]').tap(function () {
                $(this).find('.icon').toggleClass('icon-minus');
                $(this).parent().next().toggle();
            })
            $('.collapse.show').find('.collapse-header [data-role=BTButton]').addClass('btn-active')
									.find('.icon').toggleClass('icon-minus');
        },
        listCollapse: function () {
            //list-collapse 
            $('.list-collapse li > [data-role=BTButton]').tap(function () {
                $(this).toggleClass('btn-active')
						.parent().siblings().find('[data-role=BTButton]')
								.removeClass('btn-active');
            })
        }
    };


    //applist
    $('.applist .app').bind('touchstart', function () {
        $(this).addClass('btn-active');
    }).bind('touchend', function () {
        $(this).removeClass('btn-active');
    });
    //article toolbar
    $('.article').tap(function (e) {
        $(this).find('.toolbar').toggle();
        e.stopPropagation();
    });


    BingoTouch.init();
    //初始化控件
    BingoTouch.Module.Form.init();
    BingoTouch.Module.List.init();
    BingoTouch.Module.Navbar.init();
    BingoTouch.Module.Collapse.init();
});
// Page Dom Loaded
$(document).ready(function () {
    //初始化滚动列表	
    if ($('div[data-role=ScrollPanel]').length > 0) myScroll = new iScroll($('div[data-role=ScrollPanel]')[0]);
    BingoTouch.ready();

});

// Page resources loaded
window.onload = function () {
    BingoTouch.onload();
}; 